package org.bookie.model.services.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.bookie.model.Period;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * Generic implementation of the DAO services
 * 
 * @author zubairov
 *
 * @param <T>
 * @param <ID>
 */
public class GenericHibernateDAO<T, ID extends Serializable>
		implements GenericDAO<T, ID> {

	private Class<T> persistentClass;

	private Session session;

	/**
	 * Default constructor
	 *
	 */
	public GenericHibernateDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	/**
	 * Injector method
	 * @category injector
	 * @param s
	 */
	@SuppressWarnings("unchecked")
	public void setSession(Session s) {
		this.session = s;
	}

	protected Session getSession() {
		if (session == null)
			throw new IllegalStateException(
					"Session has not been set on DAO before usage");
		return session;
	}

	protected Class<T> getPersistentClass() {
		return persistentClass;
	}

	/**
	 * {@inheritDoc}
	 */
	public T findById(ID id) {
		return findById(id, false);
	}
	
	@SuppressWarnings("unchecked")
	public T findById(ID id, boolean lock) {
		T entity;
		if (lock)
			entity = (T) getSession().load(getPersistentClass(), id,
					LockMode.UPGRADE);
		else
			entity = (T) getSession().load(getPersistentClass(), id);

		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return findByCriteria();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findAllOrdered(boolean asc, String propertyName) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		crit.addOrder(asc?Order.asc(propertyName):Order.desc(propertyName));
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance, String... excludeProperty) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		crit.add(example);
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public T makePersistent(T entity) {
		getSession().saveOrUpdate(entity);
		return entity;
	}

	public void makeTransient(T entity) {
		getSession().delete(entity);
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criterion) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		for (Criterion c : criterion) {
			crit.add(c);
		}
		return crit.list();
	}

	@SuppressWarnings("unchecked")
	public T merge(T entity) {
		return (T)getSession().merge(entity);
	}
	
	protected void addPeriodCriteria(String property, Criteria criteria, Period period) {
		if (null != period && period.isValid()) {
			if (null != period.getStart()) {
				criteria.add(Restrictions.ge(property, period.getStart()));
			}
			if (null != period.getEnd()) {
				criteria.add(Restrictions.le(property, period.getEnd()));
			}
		}
	}

	public void rollbackTransaction() {
		getSession().getTransaction().rollback();
	}

}